<?php

namespace App\Http\Middleware\Custom;

use App\Utils\JWTHelper\JWTHelper;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Symfony\Component\HttpFoundation\Response;

class AuthenticationMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        //根据jwt获取user_id
        $jwttoken=$request->header('Authorization');
        $user_id=JWTHelper::getCustom($jwttoken)->id;
        // 根据user_id获取角色表的所有的权限
        $permission_ids = DB::table("user_roles as ur")
            ->join("roles as r", "ur.role_id", "=", "r.id")
            ->where("ur.user_id", "=", $user_id)
            ->pluck("r.permissions")
            ->toArray();
//        dump($permission_ids);
        // permission_ids合并成一个字符串
        $permission_ids = join(",", $permission_ids);
//        dump($permission_ids);
        // 把字符串转换成数组
        $permission_ids = explode(",", $permission_ids);
//        dump($permission_ids);
        // 数组去重
        $permission_ids = array_unique($permission_ids);
        // 获取当前请求的地址
        $currentAction=str_replace("api/","",$request->path());
        // 根据permission_id获取权限
        $allowCount = DB::table("permissions")
            ->whereIn("id", $permission_ids)
            ->where("action",$currentAction)
            ->count();
        if($allowCount == 0){
            return response()->json(["code"=>401,"msg"=>"用户未授权"]);
        }
        // 验证权限
        return $next($request);
    }
}
